package com.camel.network.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.camel.core.enums.EntityStatus;
import com.camel.core.enums.YesNo;
import com.camel.core.model.Cdrinfo;
import com.camel.network.mapper.ZsAnswerMapper;
import com.camel.network.mapper.ZsSeatMapper;
import com.camel.network.model.ZsAnswer;
import com.camel.network.model.ZsCdrinfo;
import com.camel.network.model.ZsSeat;
import com.camel.network.service.ZsCdrinfoService;
import com.camel.network.mapper.ZsCdrinfoMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
* @author 86183
* @description 针对表【zs_cdrinfo】的数据库操作Service实现
* @createDate 2024-12-05 16:45:28
*/
@Service
public class ZsCdrinfoServiceImpl extends ServiceImpl<ZsCdrinfoMapper, ZsCdrinfo>
    implements ZsCdrinfoService{

    @Autowired
    private ZsSeatMapper seatMapper;

    @Autowired
    private ZsAnswerMapper answerMapper;

    public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public boolean adds(Map<String, Cdrinfo[]> params) {
        Cdrinfo[] cdrs = params.get("cdr");
        for (Cdrinfo cdr : cdrs) {

            ZsCdrinfo cdrinfo = new ZsCdrinfo();


            // 判断是否是一个无效录音
            if(cdr.isNotValidData()) {
                System.out.println(cdr.getCallee_num() + "InValid： CallTime is Enpty Or Record File is Blank");
                continue;
            }
            // 如果被保存过就放弃
            if(isSaved(cdrinfo)) {
                System.out.println("The record has been saved ");
                continue;
            }
            // 如果推送的消息中有座席号 查出坐席，更新当前坐席绑定的人员
            if (!ObjectUtils.isEmpty(cdr.getCaller_agent_num())) {
                ZsSeat seatMod = new ZsSeat();
                seatMod.setAgentnum(cdr.getCaller_agent_num());
                seatMod.setState(1);
                seatMod.setStatus(EntityStatus.NORMAL);
                ZsSeat seat = seatMapper.selectOne(new LambdaQueryWrapper<ZsSeat>()
                        .eq(ZsSeat::getAgentnum, cdrinfo.getCallerAgentNum())
                        .eq(ZsSeat::getState, YesNo.YES.getValue())
                        .eq(ZsSeat::getStatus, EntityStatus.NORMAL));
                if(ObjectUtil.isNotEmpty(seat)) {
                    cdrinfo.setUid(seat.getUid());
                    cdrinfo.setSurveyId(seat.getSurveyId());
                }
            }
            cdrinfo.setId(UUID.randomUUID().toString());
            // 两种方式都未通过直接下一个
            // 通过call_uuid 确认答案
            if(!validAndUpdateByUUID(cdrinfo)) {
                // 通过客户号码和问卷ID定位答案
                if(!ObjectUtils.isEmpty(cdrinfo.getSurveyId()) && StringUtils.isNotBlank(cdr.getCallee_num())) {
                    validAndUpdateAnserByTaskAndPhone(cdrinfo);
                }
            }
            System.out.println("Ready Save new Cdr Info");
            save(cdrinfo);
        }

        return false;
    }

    @Override
    public boolean isSaved(ZsCdrinfo cdr) {
        QueryWrapper<ZsCdrinfo> wrapper = new QueryWrapper<>();
        wrapper.eq("call_uuid", cdr.getCallUuid());
        return count(wrapper) > 0;
    }

    public boolean validAndUpdateByUUID(ZsCdrinfo cdr) {
        if(cdr.isNotValidData()) {
            return true;
        }
        if (org.springframework.util.StringUtils.isEmpty(cdr.getUuids())) {
            System.out.println("cdr 没有UUIDS");
        } else {
            String[] uuids = cdr.getUuids().split(",");
            List<ZsAnswer> zsAnswers = new ArrayList<>();
            for (String uuid: uuids) {
                List<ZsAnswer> tmpAnswers = answerMapper.selectList(new LambdaQueryWrapper<ZsAnswer>().eq(ZsAnswer::getAgentUuid, uuid).eq(ZsAnswer::getStatus, 1));
                if(!CollectionUtils.isEmpty(tmpAnswers)) {
                    zsAnswers = tmpAnswers;
                    cdr.setId(uuid);
                    break;
                }
            }
            if(!CollectionUtils.isEmpty(zsAnswers)) {
                for (ZsAnswer zsAnswer: zsAnswers) {

                    // 录音时长和录音都不为空则表示已有录音， 不做保存
                    if(StringUtils.isNotBlank(zsAnswer.getCallLastsTime()) && StringUtils.isNotBlank(zsAnswer.getRecord())) {
                        continue;
                    }
                    updateAnswer(zsAnswer.getId(), cdr);
                }
                return true;
            }
        }
        return false;
    }

    public boolean updateAnswer(Integer answerId, ZsCdrinfo cdrinfo) {
        if(ObjectUtil.isNull(answerId)) {
            return false;
        }
        ZsAnswer answer = new ZsAnswer();
        answer.setId(answerId);
        answer.setAgentUuid(cdrinfo.getId());
        answer.setStartTime(cdrinfo.getStartTime());
        answer.setCallLastsTime(cdrinfo.getCallLastsTime());
        answer.setRecord(cdrinfo.getRecordFile());
        try {
            answer.setEndTime(sdf.format(sdf.parse(answer.getStartTime()).getTime() + Long.valueOf(answer.getCallLastsTime()) * 1000));
            answerMapper.updateById(answer);
        }catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean validAndUpdateAnserByTaskAndPhone(ZsCdrinfo zsCdrinfo) {
        String taskname = zsCdrinfo.getTaskname();
        if(zsCdrinfo.isNotValidData()) {
            return true;
        }
        if(StringUtils.isBlank(taskname)) {
            System.out.println("---------------------------taskname is null");
            return false;
        }
//        ZsCallPlan callPlan = callPlanService.selectByTaskName(zsCdrinfo.getTaskname());
//        if(ObjectUtil.isNull(callPlan)) {
//            System.out.println("未找到外呼计划");
//            return false;
//        }
        ZsAnswer answer = selectBySurveyIdAndPhone(zsCdrinfo.getSurveyId(), zsCdrinfo.getCalleeNum());
        if(ObjectUtil.isNull(answer)) {
            System.out.println("----------------------------answer has been not found ");
            return false;
        }
        // 当录音时长和录音文件都为空时 不保存
        if(StringUtils.isNotBlank(answer.getRecord()) && StringUtils.isNotBlank(answer.getCallLastsTime())) {
            return false;
        }
        return updateAnswer(answer.getId(), zsCdrinfo);
    }

    public ZsAnswer selectBySurveyIdAndPhone(Integer surveyId, String callee_num) {
        if(ObjectUtils.isEmpty(surveyId) || StringUtils.isBlank(callee_num)) {
            return null;
        }
        return answerMapper.selectOne(new LambdaQueryWrapper<ZsAnswer>()
                .eq(ZsAnswer::getSurveyId, surveyId)
                .eq(ZsAnswer::getCreator, callee_num));
    }
}




